package com.brsya.movie;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.provider.Settings;
import android.view.View;
import android.widget.FrameLayout;

import androidx.core.app.ActivityCompat;

import com.brsya.base.base.BaseMvpActivity;
import com.brsya.base.base.Contents;
import com.brsya.base.util.LoggerUtil;
import com.brsya.movie.activity.FindActivity;
import com.brsya.movie.activity.HomeActivity;
import com.brsya.movie.activity.PlayActivity;
import com.brsya.movie.application.MyApplication;
import com.brsya.movie.contract.SplashContract;
import com.brsya.movie.fragment.FindFragment;
import com.brsya.movie.presenter.SplashPresenter;
import com.brsya.movie.util.TTAdManagerHolder;
import com.brsya.movie.widget.AgreementConfigDialog;
import com.brsya.movie.widget.AgreementDialog;
import com.bytedance.novel.pangolin.NovelConfig;
import com.bytedance.novel.pangolin.NovelSDK;
import com.bytedance.novel.pangolin.PangolinDocker;
import com.bytedance.novel.pangolin.data.INovelInitListener;
import com.bytedance.novel.pangolin.data.NormalFontType;
import com.bytedance.novel.pangolin.data.ReaderFontType;
import com.bytedance.sdk.dp.DPSdk;
import com.bytedance.sdk.dp.DPSdkConfig;
import com.bytedance.sdk.openadsdk.AdSlot;
import com.bytedance.sdk.openadsdk.TTAdLoadType;
import com.bytedance.sdk.openadsdk.TTAdNative;
import com.bytedance.sdk.openadsdk.TTAdSdk;
import com.bytedance.sdk.openadsdk.TTSplashAd;
import com.bytedance.sdk.openadsdk.stub.activity.Stub_Activity;
import com.bytedance.sdk.openadsdk.stub.activity.Stub_SingleTask_Activity;
import com.bytedance.sdk.openadsdk.stub.activity.Stub_SingleTask_Activity_T;
import com.bytedance.sdk.openadsdk.stub.activity.Stub_Standard_Activity;
import com.bytedance.sdk.openadsdk.stub.activity.Stub_Standard_Activity_T;
import com.bytedance.sdk.openadsdk.stub.activity.Stub_Standard_Landscape_Activity;
import com.bytedance.sdk.openadsdk.stub.activity.Stub_Standard_Portrait_Activity;
import com.kwad.sdk.api.KsAdSDK;
import com.kwad.sdk.api.SdkConfig;
import com.ss.android.downloadlib.activity.JumpKllkActivity;
import com.ss.android.downloadlib.activity.TTDelegateActivity;
import com.ss.android.downloadlib.addownload.compliance.AppDetailInfoActivity;
import com.ss.android.downloadlib.addownload.compliance.AppPrivacyPolicyActivity;
import com.ss.android.socialbase.appdownloader.view.DownloadTaskDeleteActivity;
import com.ss.android.socialbase.appdownloader.view.JumpUnknownSourceActivity;
import com.umeng.commonsdk.UMConfigure;
import com.umeng.socialize.PlatformConfig;

import java.util.UUID;

import me.jessyan.autosize.AutoSizeConfig;

public class SplashActivity extends BaseMvpActivity<SplashPresenter> implements SplashContract.View {


    // 百度开屏广告点击跳转落地页后倒计时不暂停，即使在看落地页，倒计时结束后仍然会强制跳转，需要特殊处理：
    // 检测到广告被点击，且走了activity的onPaused证明跳转到了落地页，这时候onAdDismiss回调中不进行跳转，而是在activity的onResume中跳转。
    private boolean isBaiduSplashAd = false;
    private boolean baiduSplashAdClicked = false;
    private boolean onPaused = false;



    private static final String PREFS_SETTING = "PREFS_SETTING";


    /**
     * 广告执行完毕
     * 包括 加载失败，点击跳过， 广告播放完毕
     */
    private boolean isAdResult = false;
    /**
     * api请求完毕
     * 包括请求成功，失败
     */
    private boolean isApiResult = false;

    /**
     * mainHandler
     */
    private Handler mainHandler;
    private FrameLayout splashContainer;
    private static SharedPreferences sp;
    public static String androidId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mainHandler = new Handler(Looper.getMainLooper());

        initView();

        if (MyApplication.isAgree()) {
            loadData();
        } else {
            showAgreeDialog();
        }

    }

    @Override
    protected void initPresenter() {
        presenter = new SplashPresenter();
        presenter.attachView(this);
    }

    private void initView() {
        splashContainer = findViewById(R.id.splash_container);
    }

    @Override
    protected void onResume() {
        if (isBaiduSplashAd && onPaused && baiduSplashAdClicked) {
            // 这种情况下，百度开屏广告不能在onAdDismiss中跳转，需要自己在onResume中跳转主页。
            goToMainActivity();
        }
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        onPaused = true;
    }

    /**
     * 显示隐私协议弹框
     */
    private void showAgreeDialog() {
        AgreementDialog agreementDialog = new AgreementDialog(this);
        agreementDialog.setOnClickBtnListener(new AgreementDialog.OnClickBtnListener() {

            @Override
            public void onDismiss() {
                showAgreeDialogAgain(false);
                agreementDialog.dismiss();
            }

            @Override
            public void onConfirm() {
                MyApplication.setAgree();
                loadData();
            }
        });
        agreementDialog.show();
    }

    /**
     * 显示确认隐私协议弹框
     *
     * @param isClose 点击拒绝是否关闭
     */
    private void showAgreeDialogAgain(boolean isClose) {
        AgreementConfigDialog agreementDialog = new AgreementConfigDialog(this, !isClose);
        agreementDialog.setOnClickBtnListener(new AgreementConfigDialog.OnClickBtnListener() {
            @Override
            public void onDismiss() {
                if (isClose) {
                    finish();
                    return;
                }
                agreementDialog.dismiss();
                showAgreeDialogAgain(true);
            }

            @Override
            public void onConfirm() {
                MyApplication.setAgree();
                loadData();
            }
        });
        agreementDialog.show();
    }

    /**
     * 请求数据
     */
    public void loadData() {
        sp = getSharedPreferences(PREFS_SETTING, MODE_PRIVATE);
        androidId = Settings.System.getString(getContentResolver(), Settings.Secure.ANDROID_ID);

        if (androidId == null) {
            if (MyApplication.aCache.getAsString("deviceIdService") != null) {
                androidId = MyApplication.aCache.getAsString("deviceIdService");
            }else{
                androidId = "random" + UUID.randomUUID().toString();
                MyApplication.aCache.put("deviceIdService", androidId);
            }
        }
        presenter.getUrl();
        initDpSdk();

        initUmSdk();
    }

    private void initUmSdk() {
        //友盟正式初始化
        UMConfigure.preInit(this, Contents.YM_SDK_ID, "all");
        UMConfigure.init(this, Contents.YM_SDK_ID, "all", UMConfigure.DEVICE_TYPE_PHONE, "");
        initUmShear();
    }


    private void initUmShear(){
        // 微信设置
        PlatformConfig.setWeixin("wxdc1e388c3822c80b","3baf1193c85774b3fd9d18447d76cab0");
        PlatformConfig.setWXFileProvider(BuildConfig.APPLICATION_ID + ".fileprovider");
        // QQ设置
        PlatformConfig.setQQZone("101830139","5d63ae8858f1caab67715ccd6c18d7a5");
        PlatformConfig.setQQFileProvider(BuildConfig.APPLICATION_ID + ".fileprovider");
        // 新浪微博设置
        PlatformConfig.setSinaWeibo("3921700954","04b48b094faeb16683c32669824ebdad","http://sns.whalecloud.com");
        PlatformConfig.setSinaFileProvider(BuildConfig.APPLICATION_ID + ".fileprovider");
        // 钉钉设置
        PlatformConfig.setDing("dingoalmlnohc0wggfedpk");
        PlatformConfig.setDingFileProvider(BuildConfig.APPLICATION_ID + ".fileprovider");
        // 企业微信设置
        PlatformConfig.setWXWork("wwac6ffb259ff6f66a","EU1LRsWC5uWn6KUuYOiWUpkoH45eOA0yH-ngL8579zs","1000002","wwauthac6ffb259ff6f66a000002");
        PlatformConfig.setWXWorkFileProvider(BuildConfig.APPLICATION_ID + ".fileprovider");
        PlatformConfig.setAlipay("2015111700822536");
    }


    /**
     * 加载开屏广告
     */
    private void loadAd() {
        int width = getResources().getDisplayMetrics().widthPixels;
        int height = getResources().getDisplayMetrics().heightPixels;
        // 加载广告
        TTAdNative adNative = TTAdSdk.getAdManager().createAdNative(this);
        AdSlot adSlot = new AdSlot.Builder()
//                .setCodeId("887761715")
                .setCodeId(Contents.AD_TT_SDK_PLASH)
                //不区分渲染方式，要求开发者同时设置setImageAcceptedSize（单位：px）和setExpressViewAcceptedSize（单位：dp ）接口，不同时设置可能会导致展示异常。
                .setImageAcceptedSize(width, height)
                //                .setExpressViewAcceptedSize(xdpi, ydpi)
                .setAdLoadType(TTAdLoadType.LOAD)//推荐使用，用于标注此次的广告请求用途为预加载（当做缓存）还是实时加载，方便后续为开发者优化相关策略
                .build();

        adNative.loadSplashAd(adSlot, new TTAdNative.SplashAdListener() {
            //请求失败回调
            @Override
            public void onError(int code, String message) {
                LoggerUtil.i("穿山甲广告加载失败" + code + "--ss--" + message);
                splashContainer.setVisibility(View.GONE);

                goToMainActivity();
            }

            @Override
            public void onTimeout() {

                goToMainActivity();
            }

            @Override
            public void onSplashAdLoad(TTSplashAd ttSplashAd) {
                if (ttSplashAd == null) {
                    goToMainActivity();
                    return;
                }
                ttSplashAd.setSplashInteractionListener(new TTSplashAd.AdInteractionListener() {
                    @Override
                    public void onAdClicked(View view, int i) {
                    }

                    @Override
                    public void onAdShow(View view, int i) {

                    }

                    @Override
                    public void onAdSkip() {

                        goToMainActivity();
                    }

                    @Override
                    public void onAdTimeOver() {

                        goToMainActivity();
                    }
                });
                //获取SplashView
                View view = ttSplashAd.getSplashView();
                if (view != null && splashContainer != null && !isFinishing()) {
                    splashContainer.removeAllViews();
                    //把SplashView 添加到ViewGroup中,注意开屏广告view：width =屏幕宽；height >=75%屏幕高
                    splashContainer.addView(view);
                    //设置不开启开屏广告倒计时功能以及不显示跳过按钮,如果这么设置，您需要自定义倒计时逻辑
                    //ad.setNotAllowSdkCountdown();
                } else {
                    //开发者处理跳转到APP主页面逻辑
                        goToMainActivity();
                }
            }
        }, 4000);
    }

    /**
     * 广告加载失败
     */
    private void loadSplashAd() {
        isAdResult = true;
        if (isApiResult) {
            mainHandler.postDelayed(this::goToMainActivity, 3000);
        }
    }

    /**
     * 进入主页
     */
    private void goToMainActivity() {
        if (!isAdResult && !isApiResult) {
            return;
        }
        startActivity(new Intent(this, HomeActivity.class));

//        Intent intent = new Intent(this, FindActivity.class);
//        intent.putExtra(Contents.INTENT_FIND_SELECT, FindFragment.SELECT_CATEGORY);
//        startActivity(intent);
        finish();
    }


    /**
     * 是否授权 必要权限
     */
    private boolean permissionAgree() {
        return PackageManager.PERMISSION_GRANTED == ActivityCompat
                .checkSelfPermission(this,
                        Manifest.permission.ACCESS_NETWORK_STATE)
                && PackageManager.PERMISSION_GRANTED == ActivityCompat
                .checkSelfPermission(this,
                        Manifest.permission.ACCESS_WIFI_STATE)
                && PackageManager.PERMISSION_GRANTED == ActivityCompat
                .checkSelfPermission(this,
                        Manifest.permission.READ_PHONE_STATE);
    }

    @Override
    public void result() {
        isApiResult = true;
        if (isAdResult) {
            // 请求时间太久
            goToMainActivity();
        }
    }

    /**
     * 初始化穿山甲内容输出
     */
    public void initDpSdk() {
        TTAdManagerHolder.get().init(this, new TTAdSdk.InitCallback() {
            @Override
            public void success() {
                LoggerUtil.d("穿山甲SDK初始化成功");
                loadAd();

                DPSdkConfig.Builder builder = new DPSdkConfig.Builder()
                        .debug(true)
                        .needInitAppLog(false)
                        .initListener(new DPSdkConfig.InitListener() {
                            @Override
                            public void onInitComplete(boolean b, String s) {
                                LoggerUtil.e("初始化穿山甲内容输出= " + b + "  msg:" + s);
                            }
                        });
                DPSdk.init(SplashActivity.this, "SDK_Setting_5311893.json", builder.build());

                // 初始化穿山甲聚合广告SDK
                initBookDpSdk();
                initKSSDK(SplashActivity.this);
                clearTTActivity();
            }

            @Override
            public void fail(int i, String s) {
                LoggerUtil.i("穿山甲SDK初始化失败");
            }
        });
    }

    /**
     * 初始化穿山甲内容输出
     */
    public void initBookDpSdk() {
        NovelConfig config = new NovelConfig.Builder()
                .appName(this.getString(R.string.app_name_english)) //接入小说SDK的App的英文名 必填
                .appVersionName(BuildConfig.VERSION_NAME) //接入小说SDKApp的版本名称 必填
                .appVersionCode(BuildConfig.VERSION_CODE) //接入小说SDK App的版本号 必填
                .channel("all") //渠道号维度。开发者自定义字符串即可(建议不要包含test)。选填
                .initInnerApplog(true) // 是否使用小说sdk来初始化applog sdk。默认为false，需要开发者在App中单独初始化applog sdk，且必须在小说sdk之前初始化。
                .initInnerOpenAdSdk(false) //是否使用小说sdk来初始化广告sdk，如果为true，需要设置siteId。默认为false，需开发者在App中单独初始化广告sdk并在小说sdk之前初始化。
                .jsonFileName("SDK_Setting_5311893.json")//json配置文件的名称 必填
                .normalFontSize(NormalFontType.NORMAL) //全局字号大小 可选
                .readerFontSize(ReaderFontType.TWO) //阅读器字号大小 可选
                // 初始化成功的回调,如果初始化失败可以通过控制台，log，小说里面所有的接口调用都需要在初始化成功
                .initListener(new INovelInitListener() {
                    @Override
                    public void onInitComplete(boolean b) {

                    }
                })
                .build();


        NovelSDK.INSTANCE.attach(new PangolinDocker(config), this);
    }

    private void clearTTActivity() {
        AutoSizeConfig.getInstance().getExternalAdaptManager()
                .addCancelAdaptOfActivity(PlayActivity.class)
                .addCancelAdaptOfActivity(Stub_Activity.class)
                .addCancelAdaptOfActivity(Stub_SingleTask_Activity.class)
                .addCancelAdaptOfActivity(Stub_SingleTask_Activity_T.class)
                .addCancelAdaptOfActivity(Stub_Standard_Activity.class)
                .addCancelAdaptOfActivity(Stub_Standard_Activity_T.class)
                .addCancelAdaptOfActivity(Stub_Standard_Landscape_Activity.class)
                .addCancelAdaptOfActivity(Stub_Standard_Portrait_Activity.class)
                .addCancelAdaptOfActivity(AppPrivacyPolicyActivity.class)
                .addCancelAdaptOfActivity(AppDetailInfoActivity.class)
                .addCancelAdaptOfActivity(TTDelegateActivity.class)
                .addCancelAdaptOfActivity(JumpKllkActivity.class)
                .addCancelAdaptOfActivity(DownloadTaskDeleteActivity.class)
                .addCancelAdaptOfActivity(JumpUnknownSourceActivity.class);
    }


    public void initKSSDK(Context appContext) {
        KsAdSDK.init(appContext, new SdkConfig.Builder()
                .appId(Contents.KS_SDK_APP_ID) // 测试aapId，请联系快⼿平台申请正式AppId，必填
                .appName(getString(R.string.app_name)) // 测试appName，请填写您应⽤的名称，⾮必填
                .showNotification(true) // 是否展示下载通知栏
                .debug(BuildConfig.DEBUG) // 是否开启sdk 调试⽇志 可选
                .build());
    }
}